<template>
  <div>
    <el-button
      style="margin-left: 10px"
      v-if="!checkMode && showAll"
      type="text"
      @click="handleSelectOrg({ id: '' })"
    >
      查看全部
    </el-button>
    <el-tree
      :style="{ background: background }"
      :data="treeData"
      v-loading="loading"
      ref="treeRef"
      :props="{ label: 'name' }"
      node-key="id"
      :show-checkbox="checkMode"
      check-strictly
      :load="loadNode"
      lazy
      :class="{ checktree: checkMode }"
      :default-checked-keys="orgId"
      :highlight-current="!checkMode"
      @node-click="handleSelectOrg"
      @check-change="handleCheckChange"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <el-select
            v-if="checkMode"
            v-model="data.roleId"
            placeholder="请选择对应角色"
            size="mini"
            :style="{ width: '140px' }"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <span v-if="selectArea" class="button-area">
            <el-button @click.stop="handleArea(node,data)" type="text">区域设置</el-button>
          </span>
        </span>
      </template>
    </el-tree>
    <AreaSelectDialog
      ref="dialogRef"
      @submit="saveArea"
    />
  </div>
</template>

<script>
import { getOrgTree, getRoleList, updateAreaCode } from "@/api/system";
import AreaSelectDialog from "@/components/AreaSelectDialog.vue";
export default {
  name: "OrgTree",
  emits: ["select"],
  props: {
    showAll: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },

    checkMode: {
      // 多选模式
      type: Boolean,
      default: false,
    },
    selectArea: {
      // 选择区域
      type: Boolean,
      default: false,
    },
    orgroles: {
      type: Array,
      default: () => [],
    },
    background: {
      type: String,
      default: "#f6f9ff",
    },
  },
  components: {AreaSelectDialog},
  data() {
    return {
      firstNode: {},// 第一个节点的node
      firstResolve: null,// 第一个节点的resolve
      treeData: [],
      loading: false,
      currentOrg: {},
      roles: [],
      value: "",
      props: {
        label: "name",
        children: "children",
        isLeaf: "leaf",
      },
    };
  },
  computed: {
    orgId() {
      return this.orgroles.map((item) => item.orgId);
    },
  },
  watch: {
    orgId: {
      handler(value) {
        if (!value) {
          this.clearChecked();
        }
      },
    },
  },
  mounted() {
    // this.initOrgTree();
    this.initRolesList();
  },
  methods: {
    changeNodeData() {
      this.firstNode.childNodes = [];//把存起来的node的子节点清空，不然会界面会出现重复树！
      this.loadNode(this.firstNode, this.firstResolve);//再次执行懒加载的方法
    },
    async saveArea(data) {
      const para = {
        areaCode: data.areaCode,
        id: this.currentOrg.id
      }
      const res = await updateAreaCode(para)
      this.$refs.dialogRef.close()
      this.changeNodeData()
    },
    handleArea(node,data) {
      this.currentOrg = {...data}
      this.$refs.dialogRef.open({areaCode:data.areaCode}, true);
    },
    // 获取组织树
    async loadNode(node, resolve) {
      let id = null;
      if (node.level !== 0) {
        id = node.data.id;
      } else {
        this.firstNode = node
        this.firstResolve = resolve
      }
      const res = await getOrgTree({ parentId: id });
      resolve(res.data);
    },

    async initRolesList() {
      const res = await getRoleList();
      this.roles = res.data;
    },

    handleSelectOrg(data) {
      if (this.disabled) {
        return;
      }
      if (data.id === "") {
        this.$refs.treeRef.setCurrentKey(null); // 取消高亮
      }
      this.$emit("select", data);
    },

    clearChecked() {
      this.$refs.treeRef.setCheckedKeys([]);
    },

    handleCheckChange() {
      this.$emit(
        "update:orgroles",
        this.$refs["treeRef"].getCheckedNodes().map((item) => {
          return {
            orgId: item.id,
            roleId: item.roleId,
          };
        })
      );
    },
  },
};
</script>
<style scoped>
:deep(.el-tree-node) {
  position: relative;
}
.button-area {
  position: absolute;
  right: 10px;
  top: 5px;

}
</style>